package com.zhoulu.config;

import com.zhoulu.domain.user.UserBean;
import com.zhoulu.service.user.UserService;
import com.google.common.base.Strings;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;


public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = ((UserBean) SecurityUtils.getSubject().getPrincipal()).getUsername();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(new HashSet<>(userService.queryPermissionByUsername(username)));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("-----身份认证方法----");
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        if(Strings.isNullOrEmpty(username)){
            throw new UnknownAccountException("用户名为空");
        }
        if(Strings.isNullOrEmpty(password)){
            throw new UnknownAccountException("密码为空");
        }
        UserBean userBean = new UserBean();
        userBean.setUsername(username);
        UserBean userBeanResult = userService.queryUser(userBean);
        if(userBeanResult == null){
            throw new UnknownAccountException("用户名不存在");
        }
        if(userBeanResult.getLocked()){
            throw new LockedAccountException("该账户已锁定");
        }
        return new SimpleAuthenticationInfo(userBeanResult, userBeanResult.getPassword(), ByteSource.Util.bytes(userBeanResult.getSalt()), getName());
    }
}
